/**
 * Created by bbb on 16/9/19.
 */

import types  from './actionTypes';
import { makeRequestAction }  from './requestAction';
import { serverUrl }  from '../config/config';
import CRUD from '../config/entityOperation';
import Entities from '../constants/entities';
import { setIsFetching } from '../action/fetch';
import { REQUEST_TAIL, FAILURE_TAIL, SUCCESS_TAIL } from '../utils/actionType';
import { get, post } from '../action/request';
import {
    AsyncStorage,
} from 'react-native';

async function getToken() {
  return new Promise(function(resolve, reject) {
    AsyncStorage.getItem('assessToken',(error,result)=>{
      if (!error) {
        resolve(result);
      }else{
        reject(error)
      }
    })
  })


}


export function fetchHouseList() {

  let formData = new FormData();
  //暂时写死accsetoken

    return dispatch => {
      getToken().then((assessToken)=>{
        formData.append("accessToken",assessToken);
      dispatch(post('POST',`http://192.168.2.4:8080/yaguanapi/api/v1/house/list`,'getHouseList',formData)).then((res) => {
        console.warn('house', JSON.stringify(res))
        dispatch(receiverHouseList(res));
      })

    })}



}

export function fetchRoomList(hosueId) {
  let formData1 = new FormData();
  //暂时写死accsetoken

    return dispatch => {
      getToken().then((assessToken)=>{
        formData1.append("accessToken",assessToken);
        formData1.append("houseId",hosueId);
        console.warn('formData1++'+JSON.stringify(formData1))
      dispatch(post('POST',`http://192.168.2.4:8080/yaguanapi/api/v1/house/room/list`,'getRoomList',formData1)).then((res) => {
        console.warn('formData1res++'+JSON.stringify(res))
        dispatch(receiverRoomList(res));
      })

      })
    }


}


//设备
export function fetchDeviceList(hosueId) {
  let formData1 = new FormData();
  //暂时写死accsetoken
  formData1.append("houseId",houseId);

  return dispatch => {
    dispatch(post('POST',`http://192.168.2.4:8080/yaguanapi/api/v1/device/list`,'getDeviceList',formData1)).then((res) => {
      dispatch(receiverDeivceList(res));
    })

  }
}



export function fetchDeviceStatus(productKey, deviceName ,device ) {

    return dispatch => {
      getToken().then((assessToken)=>{
        let formData1 = new FormData();
        //暂时写死accsetoken
        formData1.append("accessToken",assessToken);
        formData1.append("productKey",productKey);
        formData1.append("deviceName",deviceName);
      dispatch(post('POST',`http://192.168.2.4:8080/yaguanapi/api/v1/device/state`,'fetchDeviceStatus',formData1)).then((res) => {
        if(res && res.object){
          const newDevice = Object.assign({}, device,JSON.parse(res && res.object))
          dispatch(UpdateDeviceInfo(newDevice))
        }

      })
      })
    }
}

export function fetchDeviceDetailById(deviceId) {

  return dispatch => {
    getToken().then((assessToken)=>{
      let formData1 = new FormData();
      //暂时写死accsetoken
      formData1.append("accessToken",assessToken);
      formData1.append("deviceId",deviceId);
      formData1.append("akeetaMock",true);
      return dispatch(post('POST',`http://192.168.2.4:8080/yaguanapi/api/v1/device/get_detail`,'fetchDeviceDetailById',formData1)).then((res) => {
        if(res && res.object){

          dispatch(UpdateDeviceInfo(res.object));
        }
        return Promise.resolve(res);


      })
    })
  }
}




export function controlDevice(params, deviceId ) {

    return dispatch => {
      getToken().then((assessToken)=>{
        let formData1 = new FormData();
        //暂时写死accsetoken
        formData1.append("accessToken",assessToken);
        formData1.append("deviceId",deviceId);
        formData1.append("setParams",JSON.stringify(params));
        formData1.append("akeetaMock",true);

      dispatch(post('POST',`http://192.168.2.4:8080/yaguanapi/api/v1/instruction/rrpc`,'controlDevice',formData1)).then((res) => {
        if(res && res.object){

          dispatch(UpdateDeviceInfo(res.object));


        }
      })
      })
    }
}

//场景

export function fetchScenesInfo(gatewayId) {


    return dispatch => {
      getToken().then((assessToken)=>{
        let formData1 = new FormData();
        //暂时写死accsetoken
        console.warn('scenceformData123123213'+JSON.stringify(formData1));
        formData1.append("accessToken",assessToken);
        formData1.append("gateWayId",gatewayId);
        console.warn('scenceformData1'+JSON.stringify(formData1));
      dispatch(post('POST',`http://192.168.2.4:8080/yaguanapi/api/v1/scene/list`,'getScenceList',formData1)).then((res) => {
        console.warn('resresresres'+JSON.stringify(res))
        dispatch(receiverScenesList(res));
      })
      })
    }
}


export function deleteScence(sceneId) {

    return dispatch => {
      return new Promise(function(resolve, reject) {
      getToken().then((assessToken)=> {
        let formData1 = new FormData();
        //暂时写死accsetoken
        formData1.append("accessToken", assessToken);
        formData1.append("sceneId", sceneId);
      dispatch(post('POST', `http://192.168.2.4:8080/yaguanapi/api/v1/scene/delete`, 'getScenceStatus', formData1)).then((res) => {
        dispatch(recevierDeletescence());
        resolve(res)

      }).catch((error) => {
        Promise.reject(error);
      })
      })
      })
    }}



export function creatScence(params) {
    return dispatch => {
      getToken().then((accessToken)=>{
        let formData1 = new FormData();
        //暂时写死accsetoken
        formData1.append("accessToken",accessToken);
        formData1.append("gateWayId",params.gatewayId);
        formData1.append("action",JSON.stringify(params.action));
        formData1.append("type",params.type);
        formData1.append("name",params.name);
        formData1.append("roomId",params.roomId);
        formData1.append("scope",params.scope);
        console.warn('formData1'+JSON.stringify(formData1))
      dispatch(post('POST',`http://192.168.2.4:8080/yaguanapi/api/v1/scene/create`,'creatScence',formData1)).then(responseData => {
        console.warn('action'+JSON.stringify(responseData))
        dispatch(receiverCreatScenes(responseData.object));

      }).catch((error) => {
      })
      })
    }
}


export function updateScence(params) {
  return dispatch => {
    return new Promise(function(resolve, reject) {
      getToken().then((accessToken)=>{
        let formData1 = new FormData();
        //暂时写死accsetoken
        formData1.append("accessToken",accessToken);
        formData1.append("action",JSON.stringify(params.action));
        formData1.append("type",params.type);
        formData1.append("sceneId",params.sceneId.toString());
        formData1.append("name",params.name);
		  console.warn('formData1'+JSON.stringify(formData1))
      dispatch(post('POST',`http://192.168.2.4:8080/yaguanapi/api/v1/scene/modify`,'modifyScence',formData1)).then(responseData => {
      	console.warn('responseData'+JSON.stringify(responseData))
        dispatch(receiverUpdateScenes(responseData.object));
        resolve(responseData)

      }).catch((error) => {
        reject(error);
      })
      })
    })
  }}



export function sortScenes(scenceIds) {
  return dispatch => {
    getToken().then((accessToken)=>{
      let ids = "";
      if (scenceIds && scenceIds.length> 0){
        ids = scenceIds.map(ele => ele.id).join(",");
      }
      let formData1 = new FormData();
      //暂时写死accsetoken
      formData1.append("accessToken",accessToken);
      formData1.append("senceIds",ids);
      dispatch(post('POST',`http://192.168.2.4:8080/yaguanapi/api/v1/scene/sortScene`,'sortScene',formData1)).then(responseData => {
        //dispatch(fetchScenesInfo(productKey, deviceName));
      }).catch((error) => {
      })
    })
    }
}








export function fetchUserInfo(user) {
  return dispatch => {
    dispatch(receiverUserInfo(user));
  }
}


//设备的操作
// export function fetchDeviceInfo(deviceInfo) {
//     return dispatch => {
//         dispatch(receiverDeviceInfo(deviceInfo));
//     }
// }
function recevierDeletescence(scence) {

  const entity = {
    name: Entities.scenes,
    operation: CRUD.DELETE,
    data: scence,
  };
  const action = makeAction(entity);
  return action;
}


export function UpdateDeviceInfo(device) {

  return dispatch => {
    dispatch(setIsFetching(`getItemMergeDeviceInfo${REQUEST_TAIL}`))
    dispatch(getItemMergeDeviceInfo(device));
    dispatch(setIsFetching(`getItemMergeDeviceInfo${SUCCESS_TAIL}`))
  }
}

//操作设备

function updateDeviceInfo(device) {
  const entity = {
    name: Entities.devices,
    operation: CRUD.UPDATE,
    data: device,
  };
  const action = makeAction(entity);
  return action;
}

function getItemMergeDeviceInfo(device) {
  const entity = {
    name: Entities.devices,
    operation: CRUD.GET_ITEM_MERGE,
    data: device,
  };
  const action = makeAction(entity);
  return action;
}


function receiverDeviceInfo(deviceInfo) {
  return {
    loading: false,
    type: types.DEVICE_LIST,
    deviceInfo
  }
}

function receiverUserInfo(user) {
  const entity = {
    name: Entities.token,
    operation: CRUD.GET_LIST,
    data: data.object,
  };
  const action = makeAction(entity);
  return action;
}


function receiverGirlList(data) {

  return {
    type: types.GIRL_LIST,
    loading: false,
    girlList: data.results
  }
}




function receiverDeivceList(data) {

  const entity = {
    name: Entities.devices,
    operation: CRUD.GET_LIST,
    data: data.object.data || [],
  };
  const action = makeAction(entity);
  return action;
}


function receiverRoomList(data) {
  console.warn('receiverRoomList' + JSON.stringify(data));
  const entity = {
    name: Entities.room,
    operation: CRUD.GET_LIST,
    data:  data ? data.object.roomList : [],
  };
  const action = makeAction(entity);
  return action;
}

function receiverHouseList(data) {
  const entity = {
    name: Entities.house,
    operation: CRUD.GET_LIST,
    data: data.object.houseList || [],
  };
  const action = makeAction(entity);
  return action;

}

function receiverScenesList(data) {

  const entity = {
    name: Entities.scenes,
    operation: CRUD.GET_LIST,
    data: data.object ? data.object.sceneList : [] ,
  };

  const action = makeAction(entity);

  return action;

}


function receiverCreatScenes(scence) {

  const entity = {
    name: Entities.scenes,
    operation: CRUD.CREATE,
    data: scence,
  };
  const action = makeAction(entity);
  return action;
}

function receiverUpdateScenes(scence) {

  const entity = {
    name: Entities.scenes,
    operation: CRUD.UPDATE,
    data: scence,
  };
  const action = makeAction(entity);
  return action;
}


// function receiverHouseList(data) {
//     return {
//         type: types.HOUSE_LIST,
//         loading: false,
//         houseList: data.object.houseList,
//
//     }}

function makeAction(entity) {
  if (entity) {

    const {
        name,
        operation,
        data,
    } = entity;
    // const  isLoading = true;
    return makeRequestAction(name, operation, data);
  }
}


